package xjtu.se.articlecommunity.buser.usermanage.impl;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import xjtu.se.articlecommunity.buser.usermanage.UserManageService;
import xjtu.se.articlecommunity.buser.usermanage.dao.UserManageDao;
import xjtu.se.articlecommunity.buser.usermanage.dto.User;
import xjtu.se.articlecommunity.buser.usermanage.dto.UserManageDto;
import xjtu.se.articlecommunity.buser.usermanage.dto.UserTab;
import xjtu.se.articlecommunity.common.Utils;
import xjtu.se.articlecommunity.common.dto.CurrentUser;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Service
@Transactional
public class UserManageServiceImpl implements UserManageService {

    @Resource
    UserManageDao userManageDao;


    @Override
    public Map<String, Object> queryUserList(UserManageDto dto) {
       return Utils.getPage(dto, ()->userManageDao.queryUserList(dto));
    }

    @Override
    public String newTab(String ut_name) {
        // 查询是否存在同名tab，若存在返回其id
        // 否则： 随机生成一个不重复的ut_id然后和ut_name一起加入数据库中
        String ut_id;
        ut_id = userManageDao.findTabByName(ut_name);
        if(ut_id!=null) return ut_id;
        do{
            ut_id = UUID.randomUUID().toString().replace("-", "");
        }while (userManageDao.findUserTabByID(ut_id)>0);

        userManageDao.newTab(ut_id, ut_name);
        return ut_id;
    }

    @Override
    public boolean hasUser(String uid) {
        return userManageDao.findUserByID(uid) > 0;
    }

    @Override
    public void setUserTab(String uid, List<String> ut_list) {
        userManageDao.rmTabForUser(uid);
        for (String ut_id :
                ut_list) {
            userManageDao.addTabToUser(uid, ut_id);
        }
    }

    @Override
    public boolean delTab(String ut_id) {
        userManageDao.dropTabInUT(ut_id);
        userManageDao.delTab(ut_id);
        return true;
    }

    @Override
    public boolean hasTabs(List<String> ut_list) {
        for (String ut_id: ut_list) {
            if (userManageDao.findUserTabByID(ut_id)<1) return false;
        }
        return true;
    }

    @Override
    public boolean setUserStatus(String u_id, int status_code) {
        return userManageDao.setUserStatus(u_id, status_code);
    }

    @Override
    public List<UserTab> queryTabListOfUser(String u_id) {
        return userManageDao.queryUserTabsByUID(u_id);
    }
}
